package jp.dev7.hongo2.util;

import java.util.List;

import jp.dev7.hongo2.entity.Question;
import android.content.Context;
import android.util.Log;

import com.db4o.Db4oEmbedded;
import com.db4o.ObjectContainer;
import com.db4o.ObjectSet;
import com.db4o.config.EmbeddedConfiguration;
import com.google.common.collect.Lists;

public class Db4oHelper {

	private static ObjectContainer db = null;

	private Context context;

	public Db4oHelper(Context context) {
		this.context = context;
	}

	private ObjectContainer db() {
		try {
			if (db == null || db.ext().isClosed()) {
				db = Db4oEmbedded.openFile(dbConfig(), db4oDBFullPath(context));
			}
			return db;
		} catch (Exception e) {
			Log.e(Db4oHelper.class.getName(), e.toString(), e);
			return null;
		}
	}

	private EmbeddedConfiguration dbConfig() {
		EmbeddedConfiguration c = Db4oEmbedded.newConfiguration();
		return c;
	}

	private String db4oDBFullPath(Context context) {
		return context.getFilesDir() + "/" + "hongo2.db4o";
	}

	public void rollback() {
		if (db != null) {
			db.rollback();
		}
	}

	public void commit() {
		db().commit();
	}

	public void close() {
		if (db != null) {
			db.close();
		}
	}

	public ObjectSet<Question> findQuestionByKey(String key) {
		Question p = new Question();
		p.key = key;
		return db().queryByExample(p);
	}

	public Question getQuestion(String key) {
		ObjectSet<Question> result = findQuestionByKey(key);
		if (result.hasNext()) {
			return result.next();
		} else {
			return null;
		}
	}

	public void saveQuestion(Question q) {

		if (getQuestion(q.key) == null) {
			db().store(q);
			Log.d("hongo", "create new data");
		} else {
			Question before = getQuestion(q.key);
			before.content = q.content;
			before.selection0 = q.selection0;
			before.selection1 = q.selection1;
			before.selection2 = q.selection2;
			before.selection3 = q.selection3;
			db().store(before);
			Log.d("hongo", "update data");
		}
	}

	public List<Question> findAllQuestion() {
		return Lists.newArrayList(db().query(Question.class));
	}

}
